<template>
	<view class="mo-sticky-wrap">
		<!--sticky 容器-->
		<view class="mo-sticky-title" :class="[isFixed === true ? 'mo-sticky-fixed' : '']" 
		:style="{transform:transform,webkitTransform:transform,'--status-barh':statusBbarHeight+'px'}">
			<slot name="header"></slot>
		</view>
		<view :style="{height:holderHeight + 'px'}" v-if="isFixed"></view>
		<!--sticky 容器-->
		<!--内容-->
		<slot />
	</view>
</template>

<script>
	const statusBbarHeight = uni.getSystemInfoSync().statusBarHeight
	export default {
		name: "moSticky",
		props: {
			scrollTop: {
				type: Number
			},
			gap: {
				type: Number,
				default: 0
			},
			nav: {
				type: Boolean,
				default: false
			}
		},
		watch: {
			scrollTop(newValue, oldValue) {
				this.updateScrollChange();
			}
		},
		// #ifdef H5
		mounted() {
			this.init();
		},
		// #endif
		onReady() {
			this.init();
		},
		data() {
			return {
				top: 0,
				height: 0,
				holderHeight: 0,
				statusBbarHeight
			};
		},
		computed:{
			transform(){
				return `translate3d(0,${this.translateY}px,0)`
			},
			overHight(){
				const statusBarh = this.statusBbarHeight + (this.nav?44:0) + this.gap
				return this.top + this.height - statusBarh
			},
			isFixed(){
				return (this.top < this.statusBbarHeight + (this.nav?44:0) && this.overHight > 0) ? true : false
			},
			translateY(){
				return (this.overHight > 0 && this.overHight < this.holderHeight) ? this.overHight - this.holderHeight : 0
			}
		},
		methods: {
			init(){
				this.updateScrollChange();
				uni.createSelectorQuery().in(this).select('.mo-sticky-title').boundingClientRect((res) => {
					if (res) {
						this.holderHeight = res.height
					}
				}).exec()
			},
			updateScrollChange() {
				const query = uni.createSelectorQuery().in(this);
				query.select('.mo-sticky-wrap').boundingClientRect((res) => {
					if (res) {
						this.top = res.top;
						this.height = res.height
					}
				}).exec()
			}
		}
	}
</script>

<style>
	.mo-sticky-fixed {
		width: 100%;
		position: fixed;
		top: 0;
		top: calc(var(--status-barh) + 44px);
		z-index: 1;
	}
</style>
